<!doctype html>
<html>
  <head>
    <title>PGlite Basic Example</title>
    <link rel="stylesheet" href="./styles.css" />
    <!-- <script src="./utils.js"></script> -->
    <script type="importmap">
      {
        "imports": {
          "@electric-sql/pglite": "../dist/index.js"
        }
      }
    </script>
  </head>
  <body>
    <h1>PGlite Basic Example</h1>
    <div class="script-plus-log">
      <script type="module">
        import { PGlite } from '@electric-sql/pglite'
        import { pgDump } from './pglite-tools/pg_dump.js'

        console.log('Starting...')

        const pg = await PGlite.create()

        console.log('Creating table...')
        await pg.exec(`
  CREATE TABLE IF NOT EXISTS test (
    id SERIAL PRIMARY KEY,
    name TEXT
  );
`)

        await pg.exec("INSERT INTO test (name) VALUES ('test');")

        await pg.exec(`
  CREATE TABLE IF NOT EXISTS test2 (
    id SERIAL PRIMARY KEY,
    name TEXT
  );
`)

        await pg.exec("INSERT INTO test2 (name) VALUES ('test2');")

        for (let i = 0; i < 50; i++) {
          await pg.exec(`INSERT INTO test2 (name) VALUES ('test2-${i}');`)
        }

        const initialSearchPath = (await pg.query('SHOW SEARCH_PATH;')).rows[0].search_path

        console.log('Dumping database...')
        const dump = await pgDump({ pg })
        console.log(dump)

        // Create a download link for the dump file
        const downloadLink = document.createElement('a')
        downloadLink.href = URL.createObjectURL(dump)
        downloadLink.download = dump.name
        downloadLink.textContent = 'Download SQL Dump'
        downloadLink.style.display = 'block'
        downloadLink.style.marginTop = '20px'
        document.body.appendChild(downloadLink)

        console.log('Restoring database...')
        const pg2 = await PGlite.create()
        const sql = await dump.text()
        await pg2.exec(sql)

        console.log('Restoring the initial search path to', initialSearchPath)
        await pg2.exec(`SET search_path TO ${initialSearchPath};`)

        console.log('Querying restored database...')
        const rows = await pg2.query('SELECT * FROM test2')
        console.log(rows)
      </script>
      <div id="log"></div>
    </div>
  </body>
</html>
